package com.lepu.app.fun.hospital;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.app.application.MyApplication;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.eyzhs.app.R;
import com.lepu.app.fun.my.adapter.AdapterQuestionList;
import com.lepu.app.fun.my.bean.BeanQuestionAnswer;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class HospitalConsultActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener,AsyncRequest,OnEditorActionListener {

	private static final String REQUEST_DATA = "request_data";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;

	// ========================================================================
	private ListView mDataListView = null;
	private AdapterQuestionList mDataAdapter = null;
	private ArrayList<BeanQuestionAnswer> mDataArrayList = null;
	
	private String mKey = "";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hospital_consult_activity);
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("常见问题");
		topbar.setonTopbarNewLeftLayoutListener(this);
		
		mDataListView = (ListView) findViewById(R.id.dataListView);
		mDataListView.setOnItemClickListener(mOnItemClickListener);
		
		mDataListView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				UtilityBase.closeSoftInput(HospitalConsultActivity.this);
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});
		
		EditText contentEditText = (EditText) findViewById(R.id.contentEditText);
		contentEditText.setOnEditorActionListener(this);
		contentEditText.setFilters(new InputFilter[]{new EmojiFilter(),new InputFilter.LengthFilter(20)});
		
		showFirstLoadDataLayout(true);
		request();
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}
	
	private void search()
	{
		EditText contentEditText = (EditText) findViewById(R.id.contentEditText);
		String content = contentEditText.getText().toString().trim();
		
		if(TextUtils.isEmpty(content))
		{
			UIHelper.showToast(HospitalConsultActivity.this, "请输入搜索内容");
			return;
		}
		
		mKey = content;
		showProgressDialog();
		request();
	}

	public void request() {

		String url = Setting.getAllQuestionsUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			if(MyApplication.getInstance().checkIsLogin())
			{
				LoginInfo loginInfo = MyApplication.getInstance()
						.getLoginInfo();
				params.put("UserID", loginInfo.UserID);
				params.put("LoginToken", loginInfo.LoginToken);
			}
			
			//params.put("CategoryID", "-1");//暂时预留

			params.put("Question", mKey);
			params.put("PageIndex", 1);
			params.put("PageSize", -1);
		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(url, map, null, this, REQUEST_DATA, true,false,true);
		
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:

				@SuppressWarnings("unchecked")
				ArrayList<BeanQuestionAnswer> dataList = (ArrayList<BeanQuestionAnswer>) msg.obj;
				if (dataList != null && dataList.size() > 0) {
					showHideNoDataLayout(false);
					mDataArrayList = dataList;
					
				} else {
					UIHelper.showToast(HospitalConsultActivity.this, R.string.no_data);
					showHideNoDataLayout(true);
					mDataArrayList = null;
				}
				
				mDataAdapter = new AdapterQuestionList(HospitalConsultActivity.this,
						mDataArrayList);
				mDataListView.setAdapter(mDataAdapter);

				showFirstLoadDataLayout(false);
				hideProgressDialog();
				break;
			case MSG_DATA_FAIL:
				showFirstLoadDataLayout(false);
				hideProgressDialog();
				
				showHideNoDataLayout(true);
				break;
			default:
				break;
			}
		};
	};
	
	private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			
			BeanQuestionAnswer item = mDataArrayList.get(position);
			
			Intent intent = new Intent(HospitalConsultActivity.this,HospitalConsultDetailActivity.class);
			intent.putExtra("question", item.ARQuestion);
			intent.putExtra("answer", item.ARAnswer);
			startActivity(intent, true);
			
		}
	};
	
	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			// 解析json data
			ArrayList<BeanQuestionAnswer> dataArraylist = BeanQuestionAnswer
					.parseJsonData((String) data);
			
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} 
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		}
	}

	private void showHideNoDataLayout(boolean isShow) {
		LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
		if (noDataLayout != null) {
			if (isShow) {
				if(mDataArrayList == null || mDataArrayList.size() ==0){
					noDataLayout.setVisibility(View.VISIBLE);
				}
			} else {
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}

	private void showFirstLoadDataLayout(boolean isShow) {
		
		LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
		noDataLayout.setVisibility(View.GONE);
		
		LinearLayout firstLoadDataLayout = (LinearLayout) findViewById(R.id.firstLoadDataLayout);
		if (firstLoadDataLayout != null) {
			if (isShow) {
				firstLoadDataLayout.setVisibility(View.VISIBLE);
			} else {
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
		case EditorInfo.IME_ACTION_SEARCH:
			
			search();
			break;
		}
		return true;
	}

}
